﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using ST.Common.Util.Model;
using ST.Common.Util.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace ST.Buz.Api
{
	/// <summary>
	/// 验证请求的头部是否包含Session Key等认证信息
	/// </summary>
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
	public class ValidateSessionAttribute : Attribute, IActionFilter
	{
		/// <summary>
		/// 未授权时返回HTTP响应代码
		/// </summary>
		public int StatusCode { get; set; }

		public ValidateSessionAttribute()
		{
			StatusCode = (int)HttpStatusCode.Unauthorized;
		}

		public ValidateSessionAttribute(HttpStatusCode statusCode = HttpStatusCode.Unauthorized)
		{
			StatusCode = (int)statusCode;
		}

		public void OnActionExecuted(ActionExecutedContext context)
		{
		}

		public void OnActionExecuting(ActionExecutingContext context)
		{
			try
			{
				UserSession sessionCurrent = HttpContextHelper.GetRawSessionFromRequest(context.HttpContext.Request, false);
			}
			catch
			{
				JsonResult result = new JsonResult(new
				{
					r = false,
					m = "未登录或登录已过期"
				});
				result.StatusCode = StatusCode;
				context.Result = result;
			}
		}
	}
}
